/***公用版js*****/
var config = require("config.js")

//是否正在登陆状态
var IsLoginState=false;

var httpHelper=function(){

  /*
  功能：httpGet封装请求
  参数: url-请求链接,
        data-请求参数,
        success-返回成功的回调,
        fail-返回失败的回调
  */
  function httpGet(url, data, success, fail){
    httpRequest(url, data, success, fail,"GET");
  }

  /*
  功能：httpPost封装请求
  参数: url-请求链接,
        data-请求参数,
        success-返回成功的回调,
        fail-返回失败的回调
  */
  function httpPost(url, data, success, fail) {
    httpRequest(url, data, success, fail, "POST");
  }

  /*
  功能：http封装请求
  参数: url-请求链接,
        data-请求参数,
        success-返回成功的回调,
        fail-返回失败的回调
        method-请求方式,
  */
  function httpRequest(url, data, success, fail, method) {
    var data = data || {};
    var userInfo = wx.getStorageSync(config.StroageKey.UserInfo);
    if (userInfo){
      //用户信息存在
      data["@sKey"] = userInfo.sKey;
      data["@sToken"] = userInfo.sToken;
      data["@iSysType"] = userInfo.iSysType;//用户类型 1-交警 2-拖车人员 3-特殊处理人员
      requestExcute(url, data, success, fail, method)
    }
    else{
      //用户信息不存在
      requestExcute(url, data, success, fail, method);
    }
  }

  /*
  功能：http封装请求
  参数: url - 请求链接,
        data - 请求参数,
        success - 返回成功的回调,
        fail - 返回失败的回调
        method - 请求方式,
  */
  function requestExcute(url, data, success, fail, method) {
    //拼接url
    url = config.host + url;
    wx.request({
      url: url,
      data: data,
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: method,
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        var result = res.data;
        if (!result.timeout) {
          if (result.success) {
            if (success)
              success(result);
          }
          else {
            if (fail)
              fail(result);
            else {
              alert(result.info,false);//提示错误信息
            }
          }
        }
        else {
          //登陆过期
          if (IsLoginState==false){
            IsLoginState=true;
          //登录超时 跳转登录页面
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }
        }
      },
      fail: function (res) {
        alert(res, false);
      },
    });
  }

  return {
    Get: httpGet,
    Post:httpPost
  }
}

/* 
功能：微信提示框
参数:msg-提示信息
     sign-true OR false
*/
function alert(msg, sign) {
  var icon = "success";
  if (sign == false) icon = "none";
  wx.showToast({
    title: msg,
    icon: icon
  });
}

module.exports = {
  http: new httpHelper(),
  alert: alert,
}



